package chen.handler;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;

import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import chen.App;
import chen.ioc.Chen;
import chen.util.ConverterUtil;
public class Context {
	public final Map<String,String> cls;
	public final Object[] aops;
	public final String[] routes;
	public final HttpServletRequest reqs;
	public final HttpServletResponse resp;
	public final ServletContext servletContext;
	public final AsyncContext async;
	public final Object instance;
	public final Method method;
	public final Map<String,Object> args;
	public Context(String[] routes,Map<String,String> cls,String[] aops,HttpServletRequest reqs,HttpServletResponse resp,ServletContext servletContext) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalStateException, IOException, ServletException{
			this.cls = cls;
			this.aops = this.converter(aops);
			this.routes = routes;
			this.reqs = reqs;
			this.resp = resp;
			this.servletContext = servletContext;
			this.instance = Chen.container.get(Class.forName(this.cls.get(this.routes[0]+"action")));
			this.method = this.instance.getClass().getMethod(routes[1],Map.class);
			this.args = ConverterUtil.arr2ObjForMap(this.reqs.getParameterMap());
			this.async = null;
	}
	public Context(String[] routes,Map<String,String> cls,String[] aops,HttpServletRequest reqs,HttpServletResponse resp,ServletContext servletContext,AsyncContext async) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalStateException, IOException, ServletException{
		this.cls = cls;
		this.aops = this.converter(aops);
		this.routes = routes;
		this.reqs = reqs;
		this.resp = resp;
		this.servletContext = servletContext;
		this.instance = Chen.container.get(Class.forName(this.cls.get(this.routes[0]+"action")));
		this.method = this.instance.getClass().getMethod(routes[1],Map.class);
		this.args = ConverterUtil.arr2ObjForMap(this.reqs.getParameterMap());
		this.async = async;
}
	
    private Object[] converter(String[] aops) throws ClassNotFoundException{
    	Object[] aopIns = null;
    	if(aops !=null && aops.length>0){
    		aopIns = new Object[aops.length];
    		for(int a=0;a<aops.length;a++){
    			aopIns[a] = Chen.container.get(Class.forName(aops[a]));
    		}
    	}
    	return aopIns;
    }
}